package com.egd.imapp.model;

import android.content.Context;

import com.egd.imapp.model.bean.UserInfo;
import com.egd.imapp.model.dao.UserAccountDao;
import com.egd.imapp.model.db.DBManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  数据模型层全局类 单例模式
 *  主要用于获取：全局线程池对象 ExecutorService、登录用户关联的全局数据库管理器对象 DBManager、
 *              用户账号操作对象 UserAccountDao
 *  初始化全局事件监听 EventListener
 */
public class Model {
    private Context mContext;
    private static final Model model = new Model();

    private ExecutorService executors = Executors.newCachedThreadPool();
    private UserAccountDao userAccountDao;
    private DBManager dbManager;

    private Model(){

    }

    public static Model getInstance(){
        return model;
    }

    public void init(Context context){

        mContext = context;

        // 创建用户账号数据库的操作类对象
        userAccountDao = new UserAccountDao(mContext);

        // 开启全局事件监听
        EventListener eventListener = new EventListener(mContext);
    }

    //获取全局线程池对象
    public ExecutorService getGlobalThreadPool(){
        return executors;
    }

    // 用户登录成功后的处理方法 重新关联一个该用户对应的DBManager对象
    public void loginSuccess(UserInfo userInfo) {
        if (userInfo == null){
            return;
        }
        if (dbManager != null){
            dbManager.close();
        }
        dbManager = new DBManager(mContext, userInfo.getName());
    }

    public DBManager getDbManager(){
        return dbManager;
    }

    public UserAccountDao getUserAccountDao(){
        return userAccountDao;
    }
}
